package com.ruoyi.web.controller.api;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ChineseToPinyin;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.fs.domain.*;
import com.ruoyi.fs.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * api
 *
 * @author hero
 */
@Anonymous
@RestController
@RequestMapping("/api")
public class APIController extends BaseController {

    @Autowired
    private IFsAddressService fsAddressService;
    @Autowired
    private IFsCourtService fsCourtService;
    @Autowired
    private IFsBatchService fsBatchService;
    @Autowired
    private IFsEvidenceRuleService fsEvidenceRuleService;
    @Autowired
    private IFsEvidenceRuleItemService fsEvidenceRuleItemService;
    @Autowired
    private IFsCapitalService fsCapitalService;
    @Autowired
    private IFsLawyerService fsLawyerService;
    @Autowired
    private IFsCaseService fsCaseService;
    @Autowired
    private IFsClientService fsClientService;
    @Autowired
    private IFsFullViewService fsFullViewService;
    @Autowired
    private IFsCaseExamineService fsCaseExamineService;
    @Autowired
    private IFsCaseFileService fsCaseFileService;
    @Autowired
    private IFsCaseRecordService fsCaseRecordService;
    @Autowired
    private IFsEntrustService fsEntrustService;
    @Autowired
    private IFsCourtAddressMappingService fsCourtAddressMappingService;
    @Autowired
    private ISysDictTypeService sysDictTypeService;
    @Autowired
    private ISysDictDataService sysDictDataService;
    @Autowired
    private ISysUserService sysUserService;

    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 根据地址获取法院信息
     */
    @GetMapping("/getCourtByAddress")
    public AjaxResult getCourtByAddress(@RequestParam(value = "dz", required = true) String dz) {
        List<FsCourtAddressMapping> mappings = fsCourtAddressMappingService.selectFsCourtAddressMappingList(new FsCourtAddressMapping());
        for (int i = 0; i < mappings.size(); i++) {
            String address = mappings.get(i).getAddress();
            if (dz.contains(address)) {
                String fymc = mappings.get(i).getFymc();
                FsCourt court = fsCourtService.selectFsCourtByFymc(fymc);
                if (court != null) {
                    return success(court);
                }
            }
        }
        String last = "";
        List<String> pcodes = new ArrayList<>();
        String l1 = "";
        if (dz.contains("省")) {
            l1 = dz.substring(0, dz.indexOf("省") + 1);
        } else if (dz.contains("自治区")) {
            l1 = dz.substring(0, dz.indexOf("自治区") + 3);
        } else if (dz.contains("市")) {
            String l = dz.substring(0, dz.indexOf("市") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(l);
            if (!list.isEmpty()) {
                FsAddress s1 = list.get(0);
                if (s1.getCode().endsWith("0000")) {
                    l1 = l;
                    pcodes.add(s1.getCode());
                }
            }
        }
        last = dz.replace(l1, "");

        String l2 = "";
        if (last.contains("自治州")) {
            l2 = last.substring(0, last.indexOf("自治州") + 3);
        } else if (last.contains("市")) {
            String s = last.substring(0, last.indexOf("市") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(s);
            if (!list.isEmpty()) {
                FsAddress s1 = list.get(0);
                if (s1.getCode().endsWith("00")) {
                    l2 = s;
                    pcodes.add(s1.getCode());
                }
            }
        } else if (last.contains("地区")) {
            l2 = last.substring(0, last.indexOf("地区") + 2);
        } else if (last.contains("盟")) {
            l2 = last.substring(0, last.indexOf("盟") + 1);
        } else if (last.contains("区")) {
            String s = last.substring(0, last.indexOf("区") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(s);
            if (!list.isEmpty()) {
                FsAddress s1 = list.get(0);
                if (s1.getCode().endsWith("00")) {
                    l2 = s;
                    pcodes.add(s1.getCode());
                }
            }
        }
        if (StringUtils.isNotBlank(l2)) {
            last = last.replace(l2, "");
        }

        FsAddress a3 = null;
        String l3 = "";
        if (last.contains("自治县")) {
            l3 = last.substring(0, last.indexOf("自治县") + 3);
        }
        if (StringUtils.isBlank(l3) && last.contains("县")) {
            String l = last.substring(0, last.indexOf("县") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(l);
            if (!list.isEmpty()) {
                l3 = l;
            } else {
                l = last.substring(0, last.indexOf("县"));
                list = fsAddressService.selectFsAddressByName(l);
                if (!list.isEmpty()) {
                    l3 = l;
                }
            }
        }
        if (StringUtils.isBlank(l3) && last.contains("区")) {
            String l = last.substring(0, last.indexOf("区") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(l);
            if (!list.isEmpty()) {
                l3 = l;
            }
        }
        if (StringUtils.isBlank(l3) && last.contains("旗")) {
            String l = last.substring(0, last.indexOf("旗") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(l);
            if (!list.isEmpty()) {
                l3 = l;
            }
        }
        if (StringUtils.isBlank(l3) && last.contains("市")) {
            String l = last.substring(0, last.indexOf("市") + 1);
            List<FsAddress> list = fsAddressService.selectFsAddressByName(l);
            if (!list.isEmpty()) {
                l3 = l;
            }
        }

        if (StringUtils.isBlank(l3)) {
            return error("无法找到对应的法院！");
        }
        if (dz.contains("津市市")) {
            l3 = "津市市";
        }
        List<FsAddress> list = fsAddressService.selectFsAddressByName(l3);
        if (!list.isEmpty() && list.size() > 1) {
            for (int i = 0; i < list.size(); i++) {
                FsAddress address = list.get(i);
                if (address.getCode().endsWith("00")) {
                    list.remove(i);
                }
            }
        }
        if (!list.isEmpty()) {
            if (list.size() == 1) {
                a3 = list.get(0);
            } else {
                for (int i = 0; i < list.size(); i++) {
                    FsAddress address = list.get(i);
                    if (pcodes.contains(address.getPcode())) {
                        a3 = address;
                        continue;
                    }
                    if (address.getPcode() != null && !"000000".equals(address.getPcode())) {
                        FsAddress p = fsAddressService.selectFsAddressByCode(address.getPcode());
                        if (pcodes.contains(p.getPcode())) {
                            a3 = address;
                            continue;
                        }
                    }
                }
            }

        }
        if (a3 == null) {
            return error("无法找到对应的法院！");
        }

        List<FsCourt> courts = fsCourtService.selectFsCourtList(a3.getCode());
        if (courts.isEmpty()) {
            return error("无法找到对应的法院！");
        }
        if (courts.size() > 1) {
            return error("找到多个对应的法院！");
        }
        return success(courts.get(0));
    }

    /**
     * 获取证据规则
     */
    @PostMapping("/test")
    public AjaxResult test(@RequestBody String json
    ) {
        System.out.println(json);
        FsLawyer lawyer = fsLawyerService.selectFsLawyerById(1L);
        return success(lawyer);
    }


    /**
     * 获取证据规则
     */
    @GetMapping("/getRule")
    public AjaxResult getRule(
            @RequestParam(value = "zfid", required = false) Long zfid,
            @RequestParam(value = "batchId", required = false) Long batchId,
            @RequestParam(value = "ajlx", required = false) String ajlx,
            @RequestParam(value = "sqlx", required = false) String sqlx
    ) {
        FsEvidenceRule query = new FsEvidenceRule();
        if (zfid != null & zfid > 0) {
            query.setZfId(zfid);
        }
        if (batchId != null & batchId > 0) {
            query.setBatchId(batchId);
        }
        if (StringUtils.isNotBlank(ajlx)) {
            query.setAjlx(ajlx);
        }
        if (StringUtils.isNotBlank(sqlx)) {
            query.setSqlx(sqlx);
        }
        List<FsEvidenceRule> rules = fsEvidenceRuleService.selectFsEvidenceRuleList(query);
        boolean ifDefault = false;
        FsEvidenceRule rule = null;
        if (rules.isEmpty()) {
            ifDefault = true;
            rule = fsEvidenceRuleService.selectFsEvidenceRuleByRuleId(1L);
        } else {
            rule = rules.get(0);
        }
        FsEvidenceRuleItem itemQuery = new FsEvidenceRuleItem();
        itemQuery.setRuleId(rule.getRuleId());
        List<FsEvidenceRuleItem> items = fsEvidenceRuleItemService.selectFsEvidenceRuleItemList(itemQuery);
        rule.setItems(items);
        if (ifDefault) {
            return AjaxResult.success("使用默认的规则", rule);
        } else {
            return AjaxResult.success("找到对应的规则", rule);
        }
    }


    /**
     * 获取委托方
     */
    @GetMapping("/getZf")
    public AjaxResult getZf(
    ) {
        FsEntrust query = new FsEntrust();
        List<FsEntrust> entrusts = fsEntrustService.selectFsEntrustList(query);
        return AjaxResult.success("成功获取", entrusts);
    }

    /**
     * 获取委托方
     */
    @GetMapping("/getZfById")
    public AjaxResult getZfById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        return AjaxResult.success(fsEntrustService.selectFsEntrustById(id));
    }

    /**
     * 获取产品批次
     */
    @GetMapping("/getBatch")
    public AjaxResult getBatch(
            @RequestParam(value = "zfid", required = true) Long zfid
    ) {
        FsBatch query = new FsBatch();
        query.setZfid(zfid);
        List<FsBatch> batches = fsBatchService.selectFsBatchList(query);
        if (!batches.isEmpty()) {
            return AjaxResult.success("成功获取", batches);
        } else {
            return AjaxResult.error("当前资方没有设置产品批次，请联系数据员处理！");
        }
    }

    /**
     * 获取产品批次
     */
    @GetMapping("/getBatchById")
    public AjaxResult getBatchById(
            @RequestParam(value = "id", required = true) Long id
    ) {
        return AjaxResult.success(fsBatchService.selectFsBatchById(id));
    }

    /**
     * 同步律师信息
     */
    @PostMapping("/editLawyer")
    public AjaxResult editLawyer(@RequestBody String json
    ) {
        JSONObject obj = JSONObject.parseObject(json);
        String xm = obj.getString("xm");
        String sfzh = obj.getString("sfzh");
        String zyjg = obj.getString("zyjg");
        String zyzh = obj.getString("zyzh");
        String bh = obj.getString("bh");
        String sjhm = obj.getString("sjhm");
        int zylb = obj.getIntValue("zylb");
        int xb = obj.getIntValue("xb");

        logger.info("同步律师信息： " + xm);
        SysUser user = sysUserService.selectUserByNickName(xm);
        if (user == null) {
            user.setNickName(xm);
            user.setUserName(ChineseToPinyin.toPinyin(xm));
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            user.setSex(xb + "");
            user.setRoleId(100L);
            user.setDeptId(104L);
            user.setStatus("0");
            user.setPhonenumber(sjhm);
            sysUserService.insertUser(user);
        }
        FsLawyer lawyer = fsLawyerService.selectFsLawyerByBh(bh);
        if (lawyer == null) {
            lawyer = new FsLawyer();
        } else {
            if (lawyer.getLastUpdateLa() != null) {
                lawyer.setLastUpdateLaStr(df.format(lawyer.getLastUpdateLa()));
            }
            if (lawyer.getLastUpdateSl() != null) {
                lawyer.setLastUpdateSlStr(df.format(lawyer.getLastUpdateSl()));
            }
            if (lawyer.getLastUpdateJa() != null) {
                lawyer.setLastUpdateJaStr(df.format(lawyer.getLastUpdateJa()));
            }
        }
        lawyer.setBh(bh);
        lawyer.setZyjg(zyjg);
        lawyer.setSfzh(sfzh);
        lawyer.setXb(xb);
        lawyer.setXm(xm);
        lawyer.setZylb(zylb);
        lawyer.setSjhm(sjhm);
        lawyer.setZyzh(zyzh);
        lawyer.setUserId(user.getUserId());
        if (lawyer.getId() != null) {
            fsLawyerService.updateFsLawyer(lawyer);
        } else {
            fsLawyerService.insertFsLawyer(lawyer);
        }
        return success(lawyer);
    }

    /**
     * 更新律师最后更新时间
     */
    @PostMapping("/updateLawyerLastTime")
    public AjaxResult updateLawyerLastTime(@RequestBody String json
    ) {
        JSONObject obj = JSONObject.parseObject(json);
        Long id = Long.parseLong(obj.getString("id"));
        String lastUpdate = obj.getString("lastUpdate");
        try {
            Date last = df.parse(lastUpdate);
            FsLawyer lawyer = fsLawyerService.selectFsLawyerById(id);
            lawyer.setLastUpdateLa(last);
            fsLawyerService.updateFsLawyer(lawyer);
            logger.info("同步律师最后更新时间： " + lawyer.getXm());
        } catch (ParseException e) {
        }
        return success();
    }

    /**
     * 同步立案信息
     */
    @PostMapping("/editCaseInfo")
    public AjaxResult editCaseInfo(@RequestBody String json) {
        JSONObject obj = JSONObject.parseObject(json);
        JSONObject localVo = obj.getJSONObject("local");
        JSONObject info = obj.getJSONObject("info");
        JSONObject detail = obj.getJSONObject("detail");
        JSONArray sh = obj.getJSONArray("sh");
        FsCase c = editCase(info, null, localVo);
        if (c.getSdbs() != null && c.getSdbs() == 1) {
            return success("手动结案，无需自动更新！");
        }
        editCaseDetailInfo(detail, c);
        if (!sh.isEmpty()) {
            editSh(sh, c);
        }
        return success();
    }

    private FsCase editCase(JSONObject obj, String ah, JSONObject localVo) {
        String localId = localVo.getString("id");
        String caseCode = localVo.getString("caseCode");
        String batchCode = localVo.getString("sysBatchCode");
        String batchId = localVo.getString("batchId");
        String detail = localVo.getString("detail");

        String ajbh = obj.getString("bh");
        String bhLs = obj.getString("bhLs");
        String ajlx = obj.getString("ajlx");
        String ajlxMc = obj.getString("ajlxMc");
        String ajmc = obj.getString("ajmc");
        String bzqx = obj.getString("bzqx");
        String fyid = obj.getString("fyid");
        String fymc = obj.getString("fymc");
        String sqbdje = obj.getString("sqbdje");
        String sqlaay = obj.getString("sqlaay");
        String sqlaayMc = obj.getString("sqlaayMc");
        String sqlx = obj.getString("sqlx");
        String sqlxMc = obj.getString("sqlxMc");
        String zt = obj.getString("zt");
        String cjsj = obj.getString("cjsj");
        String gxsj = obj.getString("zhxgsj");

        String cjrId = obj.getString("cjrId");
        FsLawyer lawyer = fsLawyerService.selectFsLawyerByBh(cjrId);
        FsCase c = null;
        if (StringUtils.isNotBlank(caseCode)) {
            c = fsCaseService.selectFsCaseByNbbh(caseCode);
        }
        if (c == null) {
            c = fsCaseService.selectFsCaseByBh(ajbh);
            if (c == null)
                c = new FsCase();
        } else {
            if (c.getBh() != null && !c.getBh().equals(ajbh)) {
                FsCaseRecord record = new FsCaseRecord();
                record.setCaseId(c.getId());
                record.setOldBh(c.getBh());
                record.setNewBh(ajbh);
                fsCaseRecordService.insertFsCaseRecord(record);
                if (c.getIfRepush() != null && c.getIfRepush() == 1) {
                    int repushNum = c.getRepushNum() + 1;
                    c.setRepushNum(repushNum);
                } else {
                    c.setIfRepush(1);
                    c.setRepushNum(1);
                }
            }
        }
        if (c.getSdbs() != null && c.getSdbs() == 1) {
            return c;
        }
        c.setBh(ajbh);
        if (StringUtils.isNotBlank(ah)) c.setAh(ah);
        if (StringUtils.isNotBlank(bhLs)) c.setBhLs(bhLs);
        if (StringUtils.isNotBlank(ajlx)) c.setAjlx(ajlx);
        if (StringUtils.isNotBlank(ajlxMc)) c.setAjlxMc(ajlxMc);
        if (StringUtils.isNotBlank(ajmc)) c.setAjmc(ajmc);
        if (StringUtils.isNotBlank(bzqx)) c.setBzqx(Integer.parseInt(bzqx));
        if (StringUtils.isNotBlank(fyid)) c.setFyid(fyid);
        if (StringUtils.isNotBlank(fymc)) c.setFymc(fymc);
        if (StringUtils.isNotBlank(sqbdje)) c.setSqbdje(new BigDecimal(sqbdje));
        if (StringUtils.isNotBlank(sqlaay)) c.setSqlaay(Integer.parseInt(sqlaay));
        if (StringUtils.isNotBlank(sqlaayMc)) c.setSqlaayMc(sqlaayMc);
        if (StringUtils.isNotBlank(sqlx)) c.setSqlx(sqlx);
        if (StringUtils.isNotBlank(sqlxMc)) c.setSqlxMc(sqlxMc);
        if (StringUtils.isNotBlank(zt)) c.setZt(Integer.parseInt(zt));
        if (StringUtils.isNotBlank(cjsj)) c.setCjsj(cjsj);
        if (StringUtils.isNotBlank(gxsj)) c.setGxsj(gxsj);
        if (StringUtils.isNotBlank(cjrId)) c.setLsbh(cjrId);
        if (StringUtils.isNotBlank(caseCode)) c.setNbajbh(caseCode);
        if (StringUtils.isNotBlank(localId)) c.setLocalId(Long.parseLong(localId));
        if (StringUtils.isNotBlank(batchCode)) c.setBatchNum(batchCode);
        if (StringUtils.isNotBlank(detail)) c.setDetailInfo(detail);
        if (lawyer != null) {
            c.setOwnerId(lawyer.getId());
            c.setOwner(lawyer.getXm());
        }
        if (StringUtils.isNotBlank(batchId)) {
            Long batchIdLong = Long.parseLong(batchId);
            c.setBatchId(batchIdLong);
            FsBatch batch = fsBatchService.selectFsBatchById(batchIdLong);
            if (batch != null) {
                c.setBatchName(batch.getBatchName());
                c.setZfid(batch.getZfid());
            }
        }

        if (StringUtils.isNotBlank(detail)) {
            JSONObject detailObj = JSONObject.parseObject(detail);
            String gstjy = detailObj.getString("gstjy");
            String shdh = detailObj.getString("shdh");
            SysUser user = null;
            if (StringUtils.isNotBlank(gstjy)) {
                if (gstjy.contains("tj001")) {
                    user = sysUserService.selectUserByUserName("tj001");
                }
                if (gstjy.contains("tj002")) {
                    user = sysUserService.selectUserByUserName("tj002");
                }
                if (gstjy.contains("tj003")) {
                    user = sysUserService.selectUserByUserName("tj003");
                }
                if (gstjy.contains("tj004")) {
                    user = sysUserService.selectUserByUserName("tj004");
                }
            } else if (StringUtils.isNotBlank(shdh)) {
                if (shdh.equals("19073173613")) {
                    user = sysUserService.selectUserByUserName("tj001");
                }
                if (shdh.equals("19073173691")) {
                    user = sysUserService.selectUserByUserName("tj002");
                }
                if (shdh.equals("19073172935")) {
                    user = sysUserService.selectUserByUserName("tj003");
                }
                if (shdh.equals("19073172875")) {
                    user = sysUserService.selectUserByUserName("tj004");
                }
            }
            if (user != null) {
                c.setTjyId(user.getUserId());
                c.setTjy(user.getNickName());
            }
        }
        if (c.getId() != null) {
            fsCaseService.updateFsCase(c);
        } else {
            fsCaseService.insertFsCase(c);
        }
        Long caseId = c.getId();
        String cailiaoList = localVo.getString("cailiaoList");
        if (StringUtils.isNotBlank(cailiaoList)) {
            fsCaseFileService.deleteFsCaseFileByCaseId(caseId);
            JSONArray clAry = JSONArray.parseArray(cailiaoList);
            for (int i = 0; i < clAry.size(); i++) {
                FsCaseFile caseFile = new FsCaseFile();
                JSONObject cl = clAry.getJSONObject(i);
                int cailiaoSubType = cl.getIntValue("cailiaoSubType");
                String cailiaoName = cl.getString("cailiaoName");
                String fileName = cl.getString("fileName");
                String filePath = cl.getString("filePath");
                String oosUrl = cl.getString("oosUrl");
                caseFile.setCaseId(caseId);
                caseFile.setType(cailiaoSubType);
                caseFile.setTypeName(cailiaoName);
                caseFile.setFileName(fileName);
                caseFile.setFilePath(filePath);
                caseFile.setOosUrl(oosUrl);
                fsCaseFileService.insertFsCaseFile(caseFile);
            }
        }
        String zhengjuList = localVo.getString("zhengjuList");
        if (StringUtils.isNotBlank(zhengjuList)) {
            JSONArray zjAry = JSONArray.parseArray(zhengjuList);
            for (int i = 0; i < zjAry.size(); i++) {
                FsCaseFile caseFile = new FsCaseFile();
                JSONObject zj = zjAry.getJSONObject(i);
                String zhengjuName = zj.getString("zhengjuName");
                String fileName = zj.getString("fileName");
                String filePath = zj.getString("filePath");
                String oosUrl = zj.getString("oosUrl");
                caseFile.setCaseId(caseId);
                caseFile.setType(4);
                caseFile.setTypeName(zhengjuName);
                caseFile.setFileName(fileName);
                caseFile.setFilePath(filePath);
                caseFile.setOosUrl(oosUrl);
                fsCaseFileService.insertFsCaseFile(caseFile);
            }
        }
        return c;
    }

    private void editCaseDetailInfo(JSONObject obj, FsCase c) {
        JSONArray dsrList = obj.getJSONArray("dsrList");
        Iterator<Object> iterator = dsrList.iterator();
        Long ygId = null;
        Long bgId = null;
        String ygbh = null;
        String bgbh = null;
        String ygmc = null;
        String bgmc = null;
        Long ssztId = null;
        while (iterator.hasNext()) {
            JSONObject dsrAry = (JSONObject) iterator.next();
            JSONArray list = dsrAry.getJSONArray("list");
            String ssdw = dsrAry.getString("ssdw");
            JSONObject dsr = (JSONObject) list.get(0);
            String dsrbh = dsr.getString("bh");
            String dsrlx = dsr.getString("dsrlx");
            String xm = dsr.getString("xm");
            String xb = dsr.getString("xb");
            String nl = dsr.getString("nl");
            String mz = dsr.getString("mz");
            String csrq = dsr.getString("csrq");
            String dzlx = dsr.getString("dzlx");
            String dz = dsr.getString("dz");
            String dwmc = dsr.getString("dwmc");
            String zy = dsr.getString("zy");
            String gzdw = dsr.getString("gzdw");
            String dwxz = dsr.getString("dwxz");
            String zzlx = dsr.getString("zzlx");
            String zzh = dsr.getString("zzh");
            String zybsjgszd = dsr.getString("zybsjgszd");
            String fddbr = dsr.getString("fddbr");
            String fddbrzw = dsr.getString("fddbrzw");
            String zjlx = dsr.getString("zjlx");
            String zjhm = dsr.getString("zjhm");
            String sjhm = dsr.getString("sjhm");
            String gddh = dsr.getString("gddh");
            String cjsj = dsr.getString("cjsj");
            String zymc = null;
            if (StringUtils.isNotBlank(zy)) {
                zymc = sysDictDataService.selectDictLabel("fs_gw_zy", zy);
            }

            FsClient client = fsClientService.selectFsClientByBh(dsrbh);
            if (client == null) {
                client = new FsClient();
            }
            client.setBh(dsrbh);
            client.setDsrlx(Integer.parseInt(dsrlx));
            if (StringUtils.isNotBlank(xm)) client.setXm(xm);
            if (StringUtils.isNotBlank(xb)) client.setXb(Integer.parseInt(xb));
            if (StringUtils.isNotBlank(nl)) client.setNl(Integer.parseInt(nl));
            if (StringUtils.isNotBlank(mz)) client.setMz(Integer.parseInt(mz));
            if (StringUtils.isNotBlank(csrq)) client.setCsrq(csrq);
            if (StringUtils.isNotBlank(dzlx)) client.setDzlx(Integer.parseInt(dzlx));
            if (StringUtils.isNotBlank(dz)) client.setDz(dz);
            if (StringUtils.isNotBlank(dwmc)) client.setDwmc(dwmc);
            if (StringUtils.isNotBlank(zy)) client.setZy(Integer.parseInt(zy));
            if (StringUtils.isNotBlank(zymc)) client.setZymc(zymc);
            if (StringUtils.isNotBlank(gzdw)) client.setGzdw(gzdw);
            if (StringUtils.isNotBlank(dwxz)) client.setDwxz(Integer.parseInt(dwxz));
            if (StringUtils.isNotBlank(zzlx)) client.setZzlx(Integer.parseInt(zzlx));
            if (StringUtils.isNotBlank(zzh)) client.setZzh(zzh);
            if (StringUtils.isNotBlank(zybsjgszd)) client.setZybsjgszd(zybsjgszd);
            if (StringUtils.isNotBlank(fddbr)) client.setFddbr(fddbr);
            if (StringUtils.isNotBlank(fddbrzw)) client.setFddbrzw(fddbrzw);
            if (StringUtils.isNotBlank(zjlx)) client.setZjlx(Integer.parseInt(zjlx));
            if (StringUtils.isNotBlank(zjhm)) client.setZjhm(zjhm);
            if (StringUtils.isNotBlank(sjhm)) client.setSjhm(sjhm);
            if (StringUtils.isNotBlank(gddh)) client.setGddh(gddh);
            if (StringUtils.isNotBlank(cjsj)) client.setCjsj(cjsj);
            if (client.getId() != null) {
                fsClientService.updateFsClient(client);
            } else {
                fsClientService.insertFsClient(client);
            }
            if ("1".equals(ssdw)) {
                ygbh = dsrbh;
                ygId = client.getId();
                ygmc = client.getDwmc();
                FsCapital capital = fsCapitalService.selectFsCapitalByName(xm);
                if (capital == null) {
                    capital = new FsCapital();
                }
                if (StringUtils.isNotBlank(dwmc)) capital.setDwmc(dwmc);
                if (StringUtils.isNotBlank(dwxz)) capital.setDwxz(Integer.parseInt(dwxz));
                if (StringUtils.isNotBlank(zzh)) capital.setZzh(zzh);
                if (StringUtils.isNotBlank(zybsjgszd)) capital.setZybsjgszd(zybsjgszd);
                if (StringUtils.isNotBlank(fddbr)) capital.setFddbr(fddbr);
                if (StringUtils.isNotBlank(fddbrzw)) capital.setFddbrzw(fddbrzw);
                if (StringUtils.isNotBlank(zjhm)) capital.setZjhm(zjhm);
                if (StringUtils.isNotBlank(sjhm)) capital.setSjhm(sjhm);
                if (StringUtils.isNotBlank(gddh)) capital.setGddh(gddh);
                if (StringUtils.isNotBlank(cjsj)) capital.setCjsj(cjsj);
                if (capital.getId() != null) {
                    fsCapitalService.updateFsCapital(capital);
                } else {
                    fsCapitalService.insertFsCapital(capital);
                }
                ssztId = capital.getId();
            } else {
                bgbh = dsrbh;
                bgId = client.getId();
                bgmc = client.getXm();
            }
        }
        c.setYg(ygId);
        c.setYgbh(ygbh);
        c.setSsztid(ssztId);
        c.setSsztmc(ygmc);
        c.setBg(bgId);
        c.setBgbh(bgbh);
        c.setBgxm(bgmc);
        fsCaseService.updateFsCase(c);
    }

    private void editSh(JSONArray ary, FsCase c) {
        Iterator<Object> iterator = ary.iterator();
        while (iterator.hasNext()) {
            JSONObject obj = (JSONObject) iterator.next();
            String caseBh = obj.getString("bhLayy");
            String shbh = obj.getString("bh");
            String shrmc = obj.getString("shrmc");
            String jbfy = obj.getString("jbfy");
            String shsj = obj.getString("shsj");
            String shyj = obj.getString("shyj");
            String bhyymc = obj.getString("bhyymc");
            String shjg = obj.getString("shjg");
            FsCaseExamine examine = fsCaseExamineService.selectFsCaseExamineByBh(shbh);
            if (examine == null) {
                examine = new FsCaseExamine();
            }
            if (c != null) {
                examine.setCaseId(c.getId());
            }
            examine.setCaseBh(caseBh);
            examine.setBh(shbh);
            if (StringUtils.isNotBlank(shrmc)) examine.setShrmc(shrmc);
            if (StringUtils.isNotBlank(jbfy)) examine.setJbfy(jbfy);
            if (StringUtils.isNotBlank(shsj)) examine.setShsj(shsj);
            if (StringUtils.isNotBlank(shyj)) examine.setShyj(shyj);
            if (StringUtils.isNotBlank(bhyymc)) examine.setBhyymc(bhyymc);
            if (StringUtils.isNotBlank(shjg)) examine.setShjg(Integer.parseInt(shjg));
            if (examine.getId() != null) {
                fsCaseExamineService.updateFsCaseExamine(examine);
            } else {
                fsCaseExamineService.insertFsCaseExamine(examine);
            }
        }
    }


    /**
     * 同步审核和结案案件信息
     */
    @PostMapping("/editShAndJaCaseInfo")
    public AjaxResult editShAndJaCaseInfo(@RequestBody String json) {
        JSONObject obj = JSONObject.parseObject(json);
        JSONObject localVo = obj.getJSONObject("local");
        JSONObject base = obj.getJSONObject("base");
        int ajzt = obj.getInteger("ajzt");
        JSONObject detail = obj.getJSONObject("detail");
        editSlja(base, detail, ajzt);
        return success();
    }

    private void editSlja(JSONObject base, JSONObject json, int ajzt) {
        String ah = base.getString("ah");
        String bh = base.getString("bh");
        String ajlx = base.getString("ajlx");
        String larqStr = base.getString("larqStr");

        FsCase c = fsCaseService.selectFsCaseByBh(bh);
        if (c == null) {
            c = new FsCase();
        } else if (c.getSdbs() != null && c.getSdbs() == 1) {
            return;
        }
        FsLawyer lawyer = null;
        String zjhm = null;
        JSONArray dlrs = json.getJSONObject("fddlr").getJSONArray("fddlrs");
        for (int i = 0; i < dlrs.size(); i++) {
            String sfzh = ((JSONObject) dlrs.get(i)).getString("zjhm");
            FsLawyer l = fsLawyerService.selectFsLawyerByZjhm(sfzh);
            if (l != null) {
                lawyer = l;
                zjhm = sfzh;
            }
        }
        FsFullView fsFullView = fsFullViewService.selectFsFullViewByBh(bh);
        if (fsFullView == null) {
            fsFullView = new FsFullView();
            JSONArray dsrList = json.getJSONArray("dsrs");
            Iterator<Object> iterator = dsrList.iterator();
            Long ygId = null;
            Long bgId = null;
            if (c == null) {
                c = new FsCase();
            }
            while (iterator.hasNext()) {
                JSONObject dsr = (JSONObject) iterator.next();
                String ssdw = dsr.getString("ssdw");
                String dsrbh = dsr.getString("bh");
                String dsrlxL = dsr.getString("dsrlx");
                String dsrlx = sysDictDataService.selectDictValue("fs_gw_dsrlx", dsrlxL);
                String mc = dsr.getString("mc");
                String xbL = dsr.getString("xb");
                String xb = sysDictDataService.selectDictValue("sys_user_sex", xbL);
                String nl = dsr.getString("nl");
                String mzL = dsr.getString("mz");
                String mz = sysDictDataService.selectDictValue("fs_gw_mz", mzL);
                String csrq = dsr.getString("csrq");
                String dzlx = dsr.getString("dzlx");
                String dsrdz = dsr.getString("dsrdz");
                String zymc = dsr.getString("zy");
                String zy = sysDictDataService.selectDictValue("fs_gw_zy", zymc);
                String gzdw = dsr.getString("gzdw");
                String dwxzL = dsr.getString("dwxz");
                String dwxz = sysDictDataService.selectDictValue("fs_gw_dwxz", dwxzL);
                String zzlxL = dsr.getString("zzlx");

                String zzlx = null;
                if (StringUtils.isNotBlank(zzlxL)) {
                    if (zzlxL.contains("信用代码")) {
                        zzlx = "4";
                    } else if (zzlxL.contains("组织机构")) {
                        zzlx = "2";
                    } else {
                        zzlx = "5";
                    }
                }
                String zzh = dsr.getString("zzhm");
                String zybsjgszd = dsr.getString("zybsjgszd");
                String fddbr = dsr.getString("fddbr");
                String fddbrzw = dsr.getString("fddbrzw");
                String zjlxL = dsr.getString("zjlx");
                String zjlx = sysDictDataService.selectDictValue("fs_gw_zjlx", zjlxL);
                String dsrzjhm = dsr.getString("zjhm");
                String dbrzjhm = dsr.getString("dbrzjhm");
                String sjhm = dsr.getString("dsrsjhm");

                FsClient client = new FsClient();
                if (StringUtils.isNotBlank(dsrbh)) client.setBh(dsrbh);
                client.setDsrlx(Integer.parseInt(dsrlx));
                if (StringUtils.isNotBlank(xb)) client.setXb(Integer.parseInt(xb));
                if (StringUtils.isNotBlank(nl)) client.setNl(Integer.parseInt(nl));
                if (StringUtils.isNotBlank(mz)) client.setMz(Integer.parseInt(mz));
                if (StringUtils.isNotBlank(csrq)) client.setCsrq(csrq);
                if (StringUtils.isNotBlank(dzlx)) client.setDzlx(Integer.parseInt(dzlx));
                if (StringUtils.isNotBlank(zy)) client.setZy(Integer.parseInt(zy));
                if (StringUtils.isNotBlank(zymc)) client.setZymc(zymc);
                if (StringUtils.isNotBlank(gzdw)) client.setGzdw(gzdw);
                if (StringUtils.isNotBlank(dwxz)) client.setDwxz(Integer.parseInt(dwxz));
                if (StringUtils.isNotBlank(zzlx)) client.setZzlx(Integer.parseInt(zzlx));
                if (StringUtils.isNotBlank(zzh)) client.setZzh(zzh);
                if (StringUtils.isNotBlank(zybsjgszd)) client.setZybsjgszd(zybsjgszd);
                if (StringUtils.isNotBlank(fddbr)) client.setFddbr(fddbr);
                if (StringUtils.isNotBlank(fddbrzw)) client.setFddbrzw(fddbrzw);
                if (StringUtils.isNotBlank(zjlx)) client.setZjlx(Integer.parseInt(zjlx));
                if (StringUtils.isNotBlank(dsrzjhm)) client.setZjhm(dsrzjhm);
                if (StringUtils.isNotBlank(dbrzjhm)) client.setZjhm(dbrzjhm);
                if (StringUtils.isNotBlank(sjhm)) client.setSjhm(sjhm);

                if ("原告".equals(ssdw)) {
                    if (StringUtils.isNotBlank(mc)) client.setDwmc(mc);
                    if (StringUtils.isNotBlank(mc)) client.setXm(mc);
                    if (StringUtils.isNotBlank(dsrdz)) client.setZybsjgszd(dsrdz);
                    if (c.getYg() != null) {
                        client.setId(c.getYg());
                        fsClientService.updateFsClient(client);
                    } else {
                        fsClientService.insertFsClient(client);
                        ygId = client.getId();
                        FsCapital capital = fsCapitalService.selectFsCapitalByName(mc);
                        if (capital == null) {
                            capital = new FsCapital();
                        }
                        if (StringUtils.isNotBlank(mc)) capital.setDwmc(mc);
                        if (StringUtils.isNotBlank(dwxz)) capital.setDwxz(Integer.parseInt(dwxz));
                        if (StringUtils.isNotBlank(zzh)) capital.setZzh(zzh);
                        if (StringUtils.isNotBlank(zybsjgszd)) capital.setZybsjgszd(zybsjgszd);
                        if (StringUtils.isNotBlank(fddbr)) capital.setFddbr(fddbr);
                        if (StringUtils.isNotBlank(fddbrzw)) capital.setFddbrzw(fddbrzw);
                        if (StringUtils.isNotBlank(zjhm)) capital.setZjhm(zjhm);
                        if (StringUtils.isNotBlank(sjhm)) capital.setSjhm(sjhm);
                        if (capital.getId() != null) {
                            fsCapitalService.updateFsCapital(capital);
                        } else {
                            fsCapitalService.insertFsCapital(capital);
                        }
                    }
                } else {
                    if (StringUtils.isNotBlank(mc)) client.setXm(mc);
                    if (StringUtils.isNotBlank(dsrdz)) client.setDz(dsrdz);
                    if (c.getBg() != null) {
                        client.setId(c.getBg());
                        fsClientService.updateFsClient(client);
                    } else {
                        fsClientService.insertFsClient(client);
                    }
                    bgId = client.getId();
                }
            }

            JSONObject jbxx = json.getJSONObject("jbxx");
            JSONObject obj = jbxx.getJSONObject("laxx");
            String ajlxMc = obj.getString("ajlx");
            String ajmc = obj.getString("ajmc");
            String fymc = obj.getString("jbfy");
            FsCourt court = fsCourtService.selectFsCourtByFymc(fymc);
            String fyid = null;
            if (court != null) {
                fyid = court.getFyid();
            }
            String sqlaayMc = obj.getString("laay");
            c.setBh(bh);
            if (StringUtils.isNotBlank(ah)) c.setAh(ah);
            if (StringUtils.isNotBlank(ajlx)) c.setAjlx(ajlx);
            if (StringUtils.isNotBlank(ajlxMc)) c.setAjlxMc(ajlxMc);
            if (StringUtils.isNotBlank(ajmc)) c.setAjmc(ajmc);
            if (StringUtils.isNotBlank(fyid)) c.setFyid(fyid);
            if (StringUtils.isNotBlank(fymc)) c.setFymc(fymc);
            if (StringUtils.isNotBlank(larqStr)) c.setGxsj(larqStr);
            if (StringUtils.isNotBlank(sqlaayMc)) c.setSqlaayMc(sqlaayMc);
            c.setAjzt(ajzt);
            if (lawyer != null) {
                c.setOwnerId(lawyer.getId());
                c.setOwner(lawyer.getXm());
            }
            c.setYg(ygId);
            c.setBg(bgId);
            if (c.getId() != null) {
                fsCaseService.updateFsCase(c);
            } else {
                fsCaseService.insertFsCase(c);
            }
        } else {
            if (c != null) {
                c.setOwnerId(lawyer.getId());
                c.setOwner(lawyer.getXm());
                fsCaseService.updateFsCase(c);
            }
        }
        fsFullView.setAh(ah);
        fsFullView.setBh(bh);

        JSONObject jbxx = json.getJSONObject("jbxx");
        JSONObject laxx = jbxx.getJSONObject("laxx");
        String ajmc = laxx.getString("ajmc");
        String larq = laxx.getString("larq");
        String laay = laxx.getString("laay");
        String sycx = laxx.getString("sycx");
        String sasj = laxx.getString("sasj");
        String jbfy = laxx.getString("jbfy");

        fsFullView.setAjmc(ajmc);
        if (StringUtils.isNotBlank(larq)) fsFullView.setLarq(larq);
        if (StringUtils.isNotBlank(laay)) fsFullView.setLaay(laay);
        if (StringUtils.isNotBlank(sycx)) fsFullView.setSycx(sycx);
        if (StringUtils.isNotBlank(sasj)) fsFullView.setSasj(sasj);
        if (StringUtils.isNotBlank(jbfy)) fsFullView.setJbfy(jbfy);

        JSONObject slxx = jbxx.getJSONObject("slxx");
        if (slxx != null) {
            String cbts = slxx.getString("cbts");
            String cbr = slxx.getString("cbr");
            if (StringUtils.isNotBlank(cbts)) fsFullView.setCbts(cbts);
            if (StringUtils.isNotBlank(cbr)) fsFullView.setCbr(cbr);
        }
        JSONObject jaxx = jbxx.getJSONObject("jaxx");
        if (jaxx != null) {
            String zdslfy = jaxx.getString("zdslfy");
            String jafs = jaxx.getString("jafs");
            String jarq = jaxx.getString("jarq");
            String jaay = jaxx.getString("jaay");
            if (StringUtils.isNotBlank(zdslfy)) fsFullView.setZdslfy(zdslfy);
            if (StringUtils.isNotBlank(jafs)) fsFullView.setJafs(jafs);
            if (StringUtils.isNotBlank(jarq)) fsFullView.setJarq(jarq);
            if (StringUtils.isNotBlank(jaay)) fsFullView.setJaay(jaay);
        }
        if (!json.getJSONArray("tsxxs").isEmpty()) {
            JSONObject tsxxs = (JSONObject) json.getJSONArray("tsxxs").get(0);
            if (tsxxs != null) {
                String ftmc = tsxxs.getString("ftmc");
                String ftyt = tsxxs.getString("ftyt");
                String kssj = tsxxs.getString("kssj");
                String jssj = tsxxs.getString("jssj");
                String gksl = tsxxs.getString("gksl");
                if (StringUtils.isNotBlank(ftmc)) fsFullView.setFtmc(ftmc);
                if (StringUtils.isNotBlank(ftyt)) fsFullView.setFtyt(ftyt);
                if (StringUtils.isNotBlank(kssj)) fsFullView.setKssj(kssj);
                if (StringUtils.isNotBlank(jssj)) fsFullView.setJssj(jssj);
                if (StringUtils.isNotBlank(gksl)) fsFullView.setGksl(gksl);
            }
        }
        if (lawyer != null) {
            fsFullView.setDlrid(lawyer.getId());
            fsFullView.setDlr(lawyer.getXm());
        }
        if (fsFullView.getId() == null) {
            fsFullViewService.insertFsFullView(fsFullView);
        } else {
            fsFullViewService.updateFsFullView(fsFullView);
        }
    }

    @GetMapping("/getCapital")
    public AjaxResult getCapital(
            @RequestParam(value = "name", required = true) String name
    ) {
        FsCapital query = new FsCapital();
        query.setDwmc(name);
        List<FsCapital> list = fsCapitalService.selectFsCapitalList(query);
        if (list.isEmpty()) {
            return error("没有找到该资方！");
        } else {
            return success(list.get(0));
        }
    }

    @PostMapping("/editCapital")
    public AjaxResult editCapital(
            FsCapital capital
    ) {
        FsCapital query = new FsCapital();
        query.setDwmc(capital.getDwmc());
        List<FsCapital> list = fsCapitalService.selectFsCapitalList(query);
        if (list.isEmpty()) {
            fsCapitalService.insertFsCapital(capital);
        } else {
            capital.setId(list.get(0).getId());
            fsCapitalService.updateFsCapital(capital);
        }
        return success();
    }


    @PostMapping("/editRule")
    public AjaxResult editRule(
            FsEvidenceRule rule
    ) {
        FsEvidenceRule query = new FsEvidenceRule();
        query.setZfName(rule.getZfName());
        query.setAjlx(rule.getAjlx());
        query.setSqlx(rule.getSqlx());
        List<FsEvidenceRule> list = fsEvidenceRuleService.selectFsEvidenceRuleList(query);
        Long ruleId;
        if (list.isEmpty()) {
            fsEvidenceRuleService.insertFsEvidenceRule(rule);
            ruleId = rule.getRuleId();
        } else {
            ruleId = list.get(0).getRuleId();
            rule.setRuleId(ruleId);
            fsEvidenceRuleService.updateFsEvidenceRule(rule);
            FsEvidenceRuleItem itemQuery = new FsEvidenceRuleItem();
            itemQuery.setRuleId(ruleId);
            List<FsEvidenceRuleItem> items = fsEvidenceRuleItemService.selectFsEvidenceRuleItemList(itemQuery);
            Long[] oldItemIds = new Long[items.size()];
            for (int i = 0; i < items.size(); i++) {
                oldItemIds[i] = items.get(i).getItemId();
            }
            fsEvidenceRuleItemService.deleteFsEvidenceRuleItemByItemIds(oldItemIds);
        }
        List<FsEvidenceRuleItem> items = rule.getItems();
        for (int i = 0; i < items.size(); i++) {
            FsEvidenceRuleItem item = items.get(i);
            item.setRuleId(ruleId);
            fsEvidenceRuleItemService.insertFsEvidenceRuleItem(item);
        }
        return success();
    }


    @PostMapping("/editCase")
    public AjaxResult editCase(
            @RequestBody String json
    ) {
        System.out.println(json);
        JSONObject obj = JSONObject.parseObject(json);

        String bh = obj.getString("bh");
        FsCase c = fsCaseService.selectFsCaseByBh(bh);
        if (c == null) {
            c = new FsCase();
        } else if (c.getSdbs() != null && c.getSdbs() == 1) {
            return success("手动结案，无需自动更新！");
        }
        String ah = obj.getString("ah");
        String bhLs = obj.getString("bhLs");
        String ajlx = obj.getString("ajlx");
        String ajlxMc = obj.getString("ajlxMc");
        String ajmc = obj.getString("ajmc");
        String bzqx = obj.getString("bzqx");
        String fyid = obj.getString("fyid");
        String fymc = obj.getString("fymc");
        String sqbdje = obj.getString("sqbdje");
        String sqlaay = obj.getString("sqlaay");
        String sqlaayMc = obj.getString("sqlaayMc");
        String sqlx = obj.getString("sqlx");
        String sqlxMc = obj.getString("sqlxMc");
        String zt = obj.getString("zt");
        String cjsj = obj.getString("cjsj");
        String gxsj = obj.getString("zhxgsj");

        String cjrId = obj.getString("cjrId");
        FsLawyer lawyer = fsLawyerService.selectFsLawyerByBh(cjrId);
        c.setBh(bh);
        if (StringUtils.isNotBlank(ah)) c.setAh(ah);
        if (StringUtils.isNotBlank(bhLs)) c.setBhLs(bhLs);
        if (StringUtils.isNotBlank(ajlx)) c.setAjlx(ajlx);
        if (StringUtils.isNotBlank(ajlxMc)) c.setAjlxMc(ajlxMc);
        if (StringUtils.isNotBlank(ajmc)) c.setAjmc(ajmc);
        if (StringUtils.isNotBlank(bzqx)) c.setBzqx(Integer.parseInt(bzqx));
        if (StringUtils.isNotBlank(fyid)) c.setFyid(fyid);
        if (StringUtils.isNotBlank(fymc)) c.setFymc(fymc);
        if (StringUtils.isNotBlank(sqbdje)) c.setSqbdje(new BigDecimal(sqbdje));
        if (StringUtils.isNotBlank(sqlaay)) c.setSqlaay(Integer.parseInt(sqlaay));
        if (StringUtils.isNotBlank(sqlaayMc)) c.setSqlaayMc(sqlaayMc);
        if (StringUtils.isNotBlank(sqlx)) c.setSqlx(sqlx);
        if (StringUtils.isNotBlank(sqlxMc)) c.setSqlxMc(sqlxMc);
        if (StringUtils.isNotBlank(zt)) c.setZt(Integer.parseInt(zt));
        if (StringUtils.isNotBlank(cjsj)) c.setCjsj(cjsj);
        if (StringUtils.isNotBlank(gxsj)) c.setGxsj(gxsj);
        if (StringUtils.isNotBlank(cjrId)) c.setLsbh(cjrId);
        if (lawyer != null) {
            c.setOwnerId(lawyer.getId());
            c.setOwner(lawyer.getXm());
        }
        if (c.getId() != null) {
            fsCaseService.updateFsCase(c);
        } else {
            fsCaseService.insertFsCase(c);
        }
        return success();
    }

    @PostMapping("/editCaseForClient")
    public AjaxResult editCaseForClient(
            @RequestBody String json
    ) {
        JSONObject obj = JSONObject.parseObject(json);
        JSONObject layy = obj.getJSONObject("layy");
        String bh = layy.getString("bh");
        FsCase c = fsCaseService.selectFsCaseByBh(bh);
        if (c == null) {
            return error("需要先调用editCase接口！");
        } else if (c.getSdbs() != null && c.getSdbs() == 1) {
            return success("手动结案，无需自动更新！");
        }
        JSONArray dsrList = obj.getJSONArray("dsrList");
        Iterator<Object> iterator = dsrList.iterator();
        Long ygId = null;
        Long bgId = null;
        String ygbh = null;
        String bgbh = null;
        String ygmc = null;
        String bgmc = null;
        Long ssztId = null;

        while (iterator.hasNext()) {
            JSONObject dsrAry = (JSONObject) iterator.next();
            JSONArray list = dsrAry.getJSONArray("list");
            String ssdw = dsrAry.getString("ssdw");
            JSONObject dsr = (JSONObject) list.get(0);
            String dsrbh = dsr.getString("bh");
            String dsrlx = dsr.getString("dsrlx");
            String xm = dsr.getString("xm");
            String xb = dsr.getString("xb");
            String nl = dsr.getString("nl");
            String mz = dsr.getString("mz");
            String csrq = dsr.getString("csrq");
            String dzlx = dsr.getString("dzlx");
            String dz = dsr.getString("dz");
            String dwmc = dsr.getString("dwmc");
            String zy = dsr.getString("zy");
            String gzdw = dsr.getString("gzdw");
            String dwxz = dsr.getString("dwxz");
            String zzlx = dsr.getString("zzlx");
            String zzh = dsr.getString("zzh");
            String zybsjgszd = dsr.getString("zybsjgszd");
            String fddbr = dsr.getString("fddbr");
            String fddbrzw = dsr.getString("fddbrzw");
            String zjlx = dsr.getString("zjlx");
            String zjhm = dsr.getString("zjhm");
            String sjhm = dsr.getString("sjhm");
            String gddh = dsr.getString("gddh");
            String cjsj = dsr.getString("cjsj");
            String zymc = null;
            if (StringUtils.isNotBlank(zy)) {
                zymc = sysDictDataService.selectDictLabel("fs_gw_zy", zy);
            }

            FsClient client = fsClientService.selectFsClientByBh(dsrbh);
            if (client == null) {
                client = new FsClient();
            }
            client.setBh(dsrbh);
            client.setDsrlx(Integer.parseInt(dsrlx));
            if (StringUtils.isNotBlank(xm)) client.setXm(xm);
            if (StringUtils.isNotBlank(xb)) client.setXb(Integer.parseInt(xb));
            if (StringUtils.isNotBlank(nl)) client.setNl(Integer.parseInt(nl));
            if (StringUtils.isNotBlank(mz)) client.setMz(Integer.parseInt(mz));
            if (StringUtils.isNotBlank(csrq)) client.setCsrq(csrq);
            if (StringUtils.isNotBlank(dzlx)) client.setDzlx(Integer.parseInt(dzlx));
            if (StringUtils.isNotBlank(dz)) client.setDz(dz);
            if (StringUtils.isNotBlank(dwmc)) client.setDwmc(dwmc);
            if (StringUtils.isNotBlank(zy)) client.setZy(Integer.parseInt(zy));
            if (StringUtils.isNotBlank(zymc)) client.setZymc(zymc);
            if (StringUtils.isNotBlank(gzdw)) client.setGzdw(gzdw);
            if (StringUtils.isNotBlank(dwxz)) client.setDwxz(Integer.parseInt(dwxz));
            if (StringUtils.isNotBlank(zzlx)) client.setZzlx(Integer.parseInt(zzlx));
            if (StringUtils.isNotBlank(zzh)) client.setZzh(zzh);
            if (StringUtils.isNotBlank(zybsjgszd)) client.setZybsjgszd(zybsjgszd);
            if (StringUtils.isNotBlank(fddbr)) client.setFddbr(fddbr);
            if (StringUtils.isNotBlank(fddbrzw)) client.setFddbrzw(fddbrzw);
            if (StringUtils.isNotBlank(zjlx)) client.setZjlx(Integer.parseInt(zjlx));
            if (StringUtils.isNotBlank(zjhm)) client.setZjhm(zjhm);
            if (StringUtils.isNotBlank(sjhm)) client.setSjhm(sjhm);
            if (StringUtils.isNotBlank(gddh)) client.setGddh(gddh);
            if (StringUtils.isNotBlank(cjsj)) client.setCjsj(cjsj);
            if (client.getId() != null) {
                fsClientService.updateFsClient(client);
            } else {
                fsClientService.insertFsClient(client);
            }
            if ("1".equals(ssdw)) {
                ygbh = dsrbh;
                ygId = client.getId();
                ygmc = client.getDwmc();
                FsCapital capital = fsCapitalService.selectFsCapitalByName(xm);
                if (capital == null) {
                    capital = new FsCapital();
                }
                if (StringUtils.isNotBlank(dwmc)) capital.setDwmc(dwmc);
                if (StringUtils.isNotBlank(dwxz)) capital.setDwxz(Integer.parseInt(dwxz));
                if (StringUtils.isNotBlank(zzh)) capital.setZzh(zzh);
                if (StringUtils.isNotBlank(zybsjgszd)) capital.setZybsjgszd(zybsjgszd);
                if (StringUtils.isNotBlank(fddbr)) capital.setFddbr(fddbr);
                if (StringUtils.isNotBlank(fddbrzw)) capital.setFddbrzw(fddbrzw);
                if (StringUtils.isNotBlank(zjhm)) capital.setZjhm(zjhm);
                if (StringUtils.isNotBlank(sjhm)) capital.setSjhm(sjhm);
                if (StringUtils.isNotBlank(gddh)) capital.setGddh(gddh);
                if (StringUtils.isNotBlank(cjsj)) capital.setCjsj(cjsj);
                if (capital.getId() != null) {
                    fsCapitalService.updateFsCapital(capital);
                } else {
                    fsCapitalService.insertFsCapital(capital);
                }
                ssztId = capital.getId();
            } else {
                bgbh = dsrbh;
                bgId = client.getId();
                bgmc = client.getXm();
            }
        }
        c.setYg(ygId);
        c.setYgbh(ygbh);
        c.setBg(bgId);
        c.setBgbh(bgbh);
        c.setSsztmc(ygmc);
        c.setSsztid(ssztId);
        c.setBgxm(bgmc);
        fsCaseService.updateFsCase(c);
        return success();
    }


    /**
     * 同步立案信息
     */
    @PostMapping("/editCaseCailiaoInfo")
    public AjaxResult editCaseCailiaoInfo(@RequestBody String json) {
        JSONObject obj = JSONObject.parseObject(json);
        JSONObject localVo = obj.getJSONObject("local");
        editCase(localVo);
        return success();
    }

    private FsCase editCase(JSONObject localVo) {
        String caseCode = localVo.getString("caseCode");

        FsCase c = null;
        if (StringUtils.isNotBlank(caseCode)) {
            c = fsCaseService.selectFsCaseByNbbh(caseCode);
        }
        if (c == null) {
            return null;
        }
        Long caseId = c.getId();
        String cailiaoList = localVo.getString("cailiaoList");
        if (StringUtils.isNotBlank(cailiaoList)) {
            fsCaseFileService.deleteFsCaseFileByCaseId(caseId);
            JSONArray clAry = JSONArray.parseArray(cailiaoList);
            for (int i = 0; i < clAry.size(); i++) {
                FsCaseFile caseFile = new FsCaseFile();
                JSONObject cl = clAry.getJSONObject(i);
                int cailiaoSubType = cl.getIntValue("cailiaoSubType");
                String cailiaoName = cl.getString("cailiaoName");
                String fileName = cl.getString("fileName");
                String filePath = cl.getString("filePath");
                String oosUrl = cl.getString("oosUrl");
                caseFile.setCaseId(caseId);
                caseFile.setType(cailiaoSubType);
                caseFile.setTypeName(cailiaoName);
                caseFile.setFileName(fileName);
                caseFile.setFilePath(filePath);
                caseFile.setOosUrl(oosUrl);
                fsCaseFileService.insertFsCaseFile(caseFile);
            }
        }
        String zhengjuList = localVo.getString("zhengjuList");
        if (StringUtils.isNotBlank(zhengjuList)) {
            JSONArray zjAry = JSONArray.parseArray(zhengjuList);
            for (int i = 0; i < zjAry.size(); i++) {
                FsCaseFile caseFile = new FsCaseFile();
                JSONObject zj = zjAry.getJSONObject(i);
                String zhengjuName = zj.getString("zhengjuName");
                String fileName = zj.getString("fileName");
                String filePath = zj.getString("filePath");
                String oosUrl = zj.getString("oosUrl");
                caseFile.setCaseId(caseId);
                caseFile.setType(4);
                caseFile.setTypeName(zhengjuName);
                caseFile.setFileName(fileName);
                caseFile.setFilePath(filePath);
                caseFile.setOosUrl(oosUrl);
                fsCaseFileService.insertFsCaseFile(caseFile);
            }
        }
        return c;
    }
}
